﻿using System.Collections.Generic;
using System.Diagnostics;

namespace PlusPlusPaint.FileIO.AST
{
    /// <summary>
    /// Class for abstracting away manipulations of the abstract syntax tree.
    /// </summary>
    class TreeFactory
    {
        #region member variables
        Stack<INode> nodeConstruction = new Stack<INode>();
        Stack<string> labels = new Stack<string>();
        #endregion

        #region public methods
        public void Reset()
        {
            nodeConstruction.Clear();
            labels.Clear();
        }

        public void CreateNewNode(INode node)
        {
            nodeConstruction.Push(node);
        }

        public void FinishAndAddTopNodeAsArg()
        {
            INode node = nodeConstruction.Pop();
            if (labels.Peek() == "")
                nodeConstruction.Peek().AddArg(node);
            else
                nodeConstruction.Peek().AddArg(labels.Peek(), node);
            labels.Pop();
        }

        public void AssociateLabel(string name)
        {
            labels.Push(name);
        }

        public void AddArgToTopNode(int i)
        {
            if (labels.Peek() == "")
                nodeConstruction.Peek().AddArg(i);
            else
                nodeConstruction.Peek().AddArg(labels.Peek(), i);
            labels.Pop();
        }

        public void AddArgToTopNode(string str)
        {
            if (labels.Peek() == "")
                nodeConstruction.Peek().AddArg(str);
            else
                nodeConstruction.Peek().AddArg(labels.Peek(), str);
            labels.Pop();
        }

        public INode ReturnTree()
        {
            Debug.Assert(nodeConstruction.Count == 1);
            INode top = nodeConstruction.Pop();
            return top;
        }
        #endregion
    }
}
